package com.cheer.job;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.cheer.dao.AccessTokenCacheDao;
import com.cheer.dao.ExPresentAudioDao;
import com.cheer.dao.ExPresentAudioGoodDao;
import com.cheer.entity.ExPresentAudioEntity;
import com.cheer.entity.ExPresentAudioGoodEntity;
import com.cheer.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author cheer
 */
@Slf4j
public class ExPresentTask implements Runnable {

    private static ExPresentAudioDao exPresentAudioDao = SpringContextUtil.getBean(ExPresentAudioDao.class);

    private static ExPresentAudioGoodDao exPresentAudioGoodDao = SpringContextUtil.getBean(ExPresentAudioGoodDao.class);

    private static RestTemplate restTemplate = SpringContextUtil.getBean(RestTemplate.class);

    private static AccessTokenCacheDao accessTokenCacheDao = SpringContextUtil.getBean(AccessTokenCacheDao.class);

    private Integer id;

    private String serviceId;

    private Semaphore semaphore;

    public ExPresentTask(Integer id, String serviceId, Semaphore semaphore) {
        this.id = id;
        this.serviceId = serviceId;
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        try {
            log.info("serviceId:" + serviceId);
            String url = String.format("https://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s",
                    accessTokenCacheDao.getAccessToken(), serviceId);

            String file = id + "-" + serviceId;
            HttpUtil.downloadFile(url, "/home/cheer/audios/" + file + ".amr");
            changeAmrToMp3("/home/cheer/audios/" + file + ".amr", "/home/cheer/audios/" + file + ".mp3");

            ExPresentAudioEntity exPresentAudioEntity = new ExPresentAudioEntity();
            exPresentAudioEntity.setId(id);
            exPresentAudioEntity.setUrl(file + ".mp3");
            exPresentAudioDao.updateById(exPresentAudioEntity);

            ExPresentAudioGoodEntity exPresentAudioGoodEntity = new ExPresentAudioGoodEntity();
            exPresentAudioGoodEntity.setId(id);
            exPresentAudioGoodEntity.setUrl(file + ".mp3");
            exPresentAudioGoodDao.updateById(exPresentAudioGoodEntity);
        } finally {
            semaphore.release();
        }
    }

    public void changeAmrToMp3(String sourcePath, String targetPath) {

        Runtime run = null;

        try {

            run = Runtime.getRuntime();

            long start = System.currentTimeMillis();

            //执行ffmpeg.exe,前面是ffmpeg.exe的地址，中间是需要转换的文件地址，后面是转换后的文件地址。-i是转换方式，意思是可编码解码，mp3编码方式采用的是libmp3lame

            //wav转pcm

            //Process p=run.exec(new File(webroot).getAbsolutePath()+"/ffmpeg -y -i "+sourcePath+" -acodec pcm_s16le -f s16le -ac 1 -ar 16000 "+targetPath);

            //mp3转pcm

            Process p = run.exec("/home/cheer/ffmpeg-4.4/ffmpeg -y -i " + sourcePath + " -ar 44100 -ac 2 -acodec mp3 " + targetPath);

            //释放进程

            p.waitFor();

            p.getOutputStream().close();

            p.getInputStream().close();

            p.getErrorStream().close();

            long end = System.currentTimeMillis();

            log.info(sourcePath + " convert success, costs:" + (end - start) + "ms");

        } catch (Exception e) {

            log.error(e.getMessage(), e);

        } finally {

            //run调用lame解码器最后释放内存

            if (run != null) {
                run.freeMemory();
            }

            FileUtil.del(sourcePath);

        }

    }

}
